<?php

namespace Biz\module\Classes;

use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\service\esSearch\Order as searchOrder;
use Biz\service\ShopInfo as sShopInfo;
use Biz\service\activity\GroupBuy as sGroupBuy;
use Biz\module\Classes\OrderRefund as clsOrderRefund;
use Biz\module\Classes\OrderInfo as clsOrderInfo;
use Biz\tools\Amount as toolAmount;
use Doraemon\pockets\constInterface\AppType;
use Doraemon\tools\HhzClient;
use Biz\module\Classes\Order as clsOrder;
use Biz\model\trade\ShopCourier as mShopCourier;
use Biz\service\activity\PinTuan as sPinTuan;
use Biz\service\Goods as sGoods;
use Biz\model\trade\OrderPackage as mOrderPackage;

class OrderList implements ActivityInfo
{
    /**
     * @param $uid
     * @param $status
     * @param $page
     * @param $pageSize
     * @param $isCommented
     * @return array
     */
    public function orderList($uid, $status, $page, $pageSize, $isCommented, $orderType = 0, $fromSource = '')
    {
        $data = [];
        $refundOrderNoList = [];
        $where['uid'] = $uid;
        $where['status[!]'] = mOrder::STATUS_DEL;
        if ($orderType == 0) {
            $where['order_type[!]'] = mOrder::ORDER_TYPE_GROUP_BUY;
        } else {
            $where['order_type'] = $orderType;
        }

        if (!empty($fromSource)) {
            $where['from_source'] = $fromSource;
        }

        if (!is_null($status)) {
            if ($status == mOrder::STATUS_SEND_OUT) {
                $status = [mOrder::STATUS_SEND_OUT, mOrder::STATUS_SEND_PART_OUT];
            }
            $where['status'] = $status;
        }

        if (!is_null($isCommented)) {
            $where['is_commented'] = $isCommented;
        }

        $list = searchOrder::getList($where, searchOrder::SCENES_APP_ORDER, 1, $page, $pageSize, 'id');

        if (!$list['total']) {
            return $data;
        }

        $orderList = mOrder::getOrderInfoList(['id' => $list['rows']]);

        $data['count'] = $list['total'];
        $data['is_over'] = $list['is_over'];

        $orderNos = array_column($orderList, 'order_no');
        $shopIds = array_column($orderList, 'shop_id');

        //获取sku信息
        $skuList = mOrderGoods::getOrderGoodsList($orderNos, [], null);

        if (empty($skuList)) {
            return $data;
        }


        //查询是否有退款中的
        $orderNoAndStatusList = array_column(array_map(function ($v) {
            return [
                'order_no' => $v['order_no'],
                'status' => $v['status']
            ];
        }, $orderList), 'status', 'order_no');


        $refundingStatusList = (new clsOrderRefund())->checkOrderHasRefunding($orderNoAndStatusList, 'userReceipt', true);


        //订单配送信息
        list($orderExpressList,$orderExpressCompanys) = mOrderPackage::getExpressCompanyList($orderNos);

        //只有来源是团购的APP才计算
        $from = HhzClient::getClientType();
        if ($from == HhzClient::APPTYPE_TUAN_MINIPROGRAM) {
            $groupBuyIds = array_filter(array_map(function ($v) {
                if ($v['promo_type'] == self::ACTIVITY_TYPE_TUAN) {
                    return $v['promo_id'];
                }

                return [];

            }, $skuList), function ($v) {
                return !empty($v);
            });

            $groupbuyList = sGroupBuy::isGroupSuccess($groupBuyIds);


        } elseif ($from == HhzClient::APPTYPE_PARAGRAPH_MINIPROGRAM) {
            //判断是节选的则查询物流公司的id

            $courierList = mShopCourier::getCourierList(['courier_id', 'courier_name'], ['courier_name' => $orderExpressCompanys]);

            $courierList = array_column($courierList, null, 'courier_name');
        }

        foreach ($skuList as $orderSku) {
            $skuInfo = [
                'sku_id' => $orderSku['sku_id'],
                'goods_id' => $orderSku['goods_id'],
                'title' => $orderSku['title'],
                'cover_img' => $orderSku['cover_img_thumb_url'],
                'sku_desc' => $orderSku['sku_desc'],
                'sell_price' => $orderSku['sell_price'],
                'buy_price' => $orderSku['integral_amount'] ? toolAmount::format(round($orderSku['pay_amount'] / $orderSku['buy_num'], 2), 2) : $orderSku['buy_price'],
                'buy_num' => $orderSku['buy_num'],
                'promo_id' => $orderSku['promo_id'],
                'promo_type' => $orderSku['promo_type'],
            ];

            if ($orderSku['promo_type'] == self::ACTIVITY_TYPE_TUAN) {
                $groupBuyOrder[$orderSku['order_no']] = $orderSku['promo_id'];
            }

            //整理数据
            $refundOrderNoList[$orderSku['order_no']][$orderSku['sku_id']] = $orderSku['refund_order_no'];

            $data['list'][$orderSku['order_no']]['sku_list'][] = $skuInfo;

            //是否参与活动
            if ($orderSku['promo_type'] > 0) {
                $activitys[$orderSku['promo_type']][] = $orderSku['order_no'];
            }
        }

        if (isset($activitys)) {
            $activity = self::getActivity($activitys, $skuList);
            $goodsList = array_column($skuList, 'goods_id');
            $goodsList = sGoods::goodsBrands($goodsList);
        }

        //查询商家信息
        $shopList = sShopInfo::getShopInfoList($shopIds);

        foreach ($orderList as $order) {

            //针对APP端，部分发货状态要转成已发货
            if ($order['status'] == mOrder::STATUS_SEND_PART_OUT) {
                $order['v_status'] = mOrder::STATUS_SEND_OUT;
            }

            $groupBuyInfo = [];
            if (isset($groupBuyOrder[$order['order_no']])) {
                if (isset($groupbuyList[$groupBuyOrder[$order['order_no']]])) {
                    $groupBuyInfo = $groupbuyList[$groupBuyOrder[$order['order_no']]];
                }
            }


            $shopInfo = $shopList[$order['shop_id']];

            $data['list'][$order['order_no']] = [
                'order_no' => $order['order_no'],
                'message' => $order['message'],
                'status' => $order['v_status'],
                'groupbuy' => $groupBuyInfo,
                'shop_info' => [
                    'shop_id' => $order['shop_id'],
                    'shop_name' => $shopInfo['shop_name'],
                    'imgurl' => $shopInfo['shop_imgurl_small'],
                    'cover_img' => $shopInfo['shop_imgurl_small'],
                    'shop_icon' => $shopInfo['shop_imgurl_small'],
                    'status' => $shopInfo['status'],
                ],
                'sku_list' => $data['list'][$order['order_no']]['sku_list'],
                'summary' => [
                    'pay_amount' => $order['pay_amount'],
                    'shipping_amount' => $order['shipping_amount'],
                ],
                'integral' => [
                    'discount' => $order['integral_amount']
                ],
                'time_info' => [
                    'add_time' => $order['addtime'],
                    'now_time' => date('Y-m-d H:i:s'),
                ]
            ];

            //节选小程序会返回物流公司ID
            if (isset($courierList)) {
                $expressCompany = isset($orderExpressList[$order['order_no']]) ? $orderExpressList[$order['order_no']][0]['express_company'] : '';

                if (!empty($expressCompany)) {
                    $data['list'][$order['order_no']]['courier_id'] = $courierList[$expressCompany]['courier_id'];
                }
            }


            if ($order['status'] == mOrder::STATUS_NORMAL && isset($order['paystop_time'])) {
                $data['list'][$order['order_no']]['time_info']['paystop_time'] = $order['paystop_time'];
            } elseif ($order['status'] == mOrder::STATUS_SEND_OUT && isset($order['autoconfirm_time'])) {

                //如果是有在进行中的退款申请，那么在详情页就不显示自动确认收货的倒计时
                if ((
                        isset($refundingStatusList[$order['order_no']])
                        && !in_array($refundingStatusList[$order['order_no']], [
                            clsOrderRefund::REFUNDING_YES,
                            clsOrderRefund::REFUNDING_RIGHTS_IN
                        ])) ||
                    !isset($refundingStatusList[$order['order_no']])) {
                    $data['list'][$order['order_no']]['time_info']['autoconfirm_time'] = $order['autoconfirm_time'];
                    $data['list'][$order['order_no']]['time_info']['maxprolong_time'] = $order['maxprolong_time'];
                }

            }


            //判断时间是否正常
            $data['list'][$order['order_no']]['time_info'] = array_filter(array_map(function ($v) {
                return strtotime($v);
            }, $data['list'][$order['order_no']]['time_info']), function ($v) {
                if ($v > 0) {
                    return true;
                }
                return false;
            });


            //订单列表页展示退款状态
            $refundOrderNos = isset($refundOrderNoList[$order['order_no']]) ? $refundOrderNoList[$order['order_no']] : [];
            $refundInfoList = OrderRefundInfo::getRefundStatusInfo($order['status'], $refundOrderNos, 'list');

            //refundInfo初始化并赋值
            $refundInfo = null;
            if (key_exists($order['status'], mOrder::$paiedStatusList) || ($order['cancel_type'] == 0 && $order['status'] == mOrder::STATUS_CLOSE)) {
                foreach ($data['list'][$order['order_no']]['sku_list'] as &$skuInfo) {
                    $refundInfo = !empty($refundInfoList[$skuInfo['sku_id']]) ? $refundInfoList[$skuInfo['sku_id']] : null;
                    $skuInfo['refund_info'] = $refundInfo;
                }
            }


            //获取订单参与的活动信息
            if (isset($activity) && !empty($activity)) {
                foreach ($activity as $_ak => &$_av) {
                    if (isset($_av[$order['order_no']])) {
                        $data['list'][$order['order_no']][$_ak] = $_av[$order['order_no']];
                        //分享
                        if ($_ak == 'team_join_info') {
                            $share_info[$_av[$order['order_no']]['goods_id']] = [
                                'team_join_id' => $_av[$order['order_no']]['team_join_id'],
                                'group_buy_price' => $_av[$order['order_no']]['group_buy_price']
                            ];
                        }
                        if (isset($share_info)) {
                            $goodsLists = array_column($goodsList, NUll, 'goods_id');
                            $goodsShare = sGoods::goodsPintuanShare([$goodsLists[$data['list'][$order['order_no']]['team_join_info']['goods_id']]], $share_info[$data['list'][$order['order_no']]['team_join_info']['goods_id']]);
                            if (isset($goodsShare[$data['list'][$order['order_no']]['team_join_info']['goods_id']])) {
                                $data['list'][$order['order_no']]['share_info'] = $goodsShare[$data['list'][$order['order_no']]['team_join_info']['goods_id']];
                            }
                        }
                    }
                    if ($_ak == $order['order_no']) {
                        $data['list'][$order['order_no']]['sku_list'][0] = array_merge($data['list'][$order['order_no']]['sku_list'][0], $_av);
                    }
                }
            }


        }

        if (!empty($data['list'])) {
            $data['list'] = array_values($data['list']);

            $sortAddtime = array_map(function ($v) {
                return $v['time_info']['add_time'];
            }, $data['list']);

            array_multisort($sortAddtime, SORT_DESC, SORT_NUMERIC, $data['list']);
        }

        return $data;
    }

    private static function getActivity($activity, $skuList)
    {
        $data = [];
        foreach (ActivityInfo::ACTIVITY_TYPES_MAPS as $_k => $_v) {
            switch ($_k) {
                case ActivityInfo::ACTIVITY_TYPE_PINTUAN;
                    $data = sPinTuan::getSkuOrder($activity[ActivityInfo::ACTIVITY_TYPE_PINTUAN], $skuList);
                    break;
            }
        }
        return $data;
    }

    public static function detectFromSourceAndOrderType()
    {

        $appType = HhzClient::getClientType();

        $fromSource = clsOrder::getOrderFromSource($appType);

        if ($fromSource == mOrder::FROM_SOURCE_WX_MINI || $fromSource == mOrder::FROM_SOURCE_APP) {
            $fromSource = [mOrder::FROM_SOURCE_APP, mOrder::FROM_SOURCE_WX_MINI];
        }


        $orderType = mOrder::ORDER_TYPE_NORMAL;
        if ($appType == HhzClient::APPTYPE_TUAN_MINIPROGRAM) {
            $orderType = mOrder::ORDER_TYPE_GROUP_BUY;
        }

        return [
            $fromSource,
            $orderType
        ];
    }


}